package com.example.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.example.entity.UsersEntity;
import com.example.util.TokenUtil;

/**
 * 身份验证：token拦截器 拦截所有请求（除了登录） 1、获取请求里的token 2、验证token是否正确
 * 
 * @author Administrator
 *
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 如果不是映射到方法直接通过
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		// 设置响应的编码
		response.setCharacterEncoding("utf-8");
		// 获取参数token
		String tokenStr = request.getParameter("token");
		// 验证token
		if (tokenStr != null && tokenStr != "") {
			try {
				UsersEntity admin = TokenUtil.unsign(tokenStr, UsersEntity.class);
				if (admin != null) {
					// 如果能解密成功，说明验证通过
					System.out.println(admin);
					return true;
				}
			} catch (Exception e) {

			}
		}
		// 否则，验证不通过，返回失败信息
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		JSONObject json = new JSONObject();
		json.put("success", "false");
		json.put("msg", "身份认证失败");
		json.put("code", "500");
		response.getWriter().append(json.toString());
		System.out.println("认证失败");
		return false;
	}
}
